const { Service } = require('egg')

class UserService extends Service {
  async findUser(data) {
    // 查询用户
    const user_info = await this.app.mysql.get('user_info', data);
    return { user_info }
  }

  async findUserRole(role_id) {
    // 获取用户角色
    const role_info = await this.app.mysql.get('role_info', { role_id });
    // 查询用户权限
    const ps_info = await this.app.mysql.select('ps_info', {
      where: { ps_id: role_info.ps_ids.split(',') }, // WHERE 条件
      columns: ['ps_id', 'ps_name', 'ps_pid', 'ps_level'], // 要查询的表字段
    })
    // 获取用户访问权限
    const ps_api_info = await this.app.mysql.select('ps_api_info', {
      where: { ps_id: role_info.ps_ids.split(',') }, // WHERE 条件
      columns: ['id', 'ps_id', 'ps_api_path', 'ps_api_service', 'ps_api_order'], // 要查询的表字段
    })

    // 合并查询结果
    const list = ps_info.map(v => {
      const s = ps_api_info.find(item => v.ps_id === item.ps_id)
      return { ...v, ...s }
    })
    // 查询第一层路由和导航菜单
    const reuslt = list.filter(v => v.ps_level === 0).sort((a, b) => {
      return a.ps_api_order - b.ps_api_order
    })

    // 查询第二层路由和导航菜单  
    list.forEach(v => {
      // 查询二级
      if (v.ps_level === 1) {
        // 找到所属一级位置
        const s = reuslt.find(item => item.ps_id === v.ps_pid)
        // 
        if (s) {
          if (!s.children) {
            s.children = []
          }
          s.children.push(v)
        }
      }
    })

    // 排序二级
    list.forEach(v => {
      v.children && v.children.sort((a, b) => {
        return a.ps_api_order - b.ps_api_order
      })
    })

    // 排序
    return {
      role_name: role_info.role_name,
      routes: reuslt,
    }
  }

  async getUsers() {
    const users = await this.app.mysql.query("select id,user,user_name,role_name,ps_ids,user_info.role_id from user_info, role_info where user_info.role_id=role_info.role_id ")

    for (let i = 0; i < users.length; i++) {
      users[i].permission_list = await this.app.mysql.select('ps_info', {
        where: {
          ps_id: users[i].ps_ids.split(',')
        }
      })
    }

    return users
  }

  async getPsInfo() {
    const result = await this.app.mysql.select('ps_info', {
      columns: ["ps_id", "ps_name"]
    })
    return result
  }

  async modifyUserPermission({ role_id, ps_ids }) {
    const row = {
      ps_ids
    };

    const options = {
      where: {
        role_id
      }
    };
    const result = await this.app.mysql.update('role_info', row, options); // 更新  
    return result.affectedRows === 1
  }
}

module.exports = UserService